<template>
  <div v-loading="detailInfoShow">
    <div
      class="requestAdd"
      v-if="
        !selectionMaterialShow &&
        !requestAddShow &&
        !paymentAddShow &&
        !inorderAddShow
      "
    >
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check'"
          class="btn save"
          @click="handleCheckBtn2('', 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check'"
          class="btn withdraw"
          @click="handleCheckBtn2('', 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check'"
          class="btn withdraw"
          @click="handleCheckBtn2('', 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >提交</el-button
        >

        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <!-- <el-button
          v-if="activeName == 'approval' && flowInfoList.length"
          @click="handleEvaluate()"
          class="btn save"
          ><el-icon class="icon" color="#fff"> <Comment /> </el-icon
          >评论</el-button
        > -->
        <el-button
          v-if="activeName == 'approval' && flowInfoList.length"
          @click="handlePrint()"
          v-print="prints"
          class="btn add"
          ><el-icon class="icon" color="#fff"> <Printer /> </el-icon
          >打印</el-button
        >
        <!-- <el-button
          v-if="
            pageType === 'detail' &&
            requestForm.contractCheckStatus === 3 &&
            route.name === 'ContractSeal' &&
            requestForm.contractType !== 2 &&
            requestForm.supplement !== 1
          "
          class="btn add"
          @click="handleAddPayment()"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >申请付款</el-button
        >
        <el-button
          v-if="
            pageType === 'detail' &&
            requestForm.contractCheckStatus === 3 &&
            route.name === 'ContractSeal' &&
            requestForm.contractType !== 2 &&
            requestForm.supplement !== 1
          "
          class="btn add"
          @click="handleAddTicket()"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增到票</el-button
        >
        <el-button
          v-if="
            pageType === 'detail' &&
            requestForm.contractCheckStatus === 3 &&
            route.name === 'ContractSeal' &&
            requestForm.contractType !== 2 &&
            requestForm.supplement !== 1
          "
          class="btn add"
          @click="handleAddInorder()"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增入库</el-button
        > -->
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-tabs
        type="border-card"
        v-model="activeName"
        @tab-change="activeNamechange"
      >
        <el-tab-pane label="合同用印信息" name="info">
          <el-collapse v-model="activeNames">
            <!-- 基础信息 -->
            <el-collapse-item
              name="1"
              v-if="!contactAddShow"
              class="transform-down"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title"
                  >{{
                    pageType !== "detail" && pageType !== "check "
                      ? pageType === "add"
                        ? "新增"
                        : "编辑"
                      : ""
                  }}合同用印信息</span
                >
              </template>
              <div class="request-info">
                <el-form
              :model="requestForm"
              ref="requestFormRef"
              :rules="queryRules"
              label-width="130px"
              v-enterToNext
              :disabled="pageType === 'detail' || pageType === 'check'"
            >
              <el-row>
                <el-col :span="6">
                  <el-form-item label="合同编号：">
                    <el-input
                      disabled
                      v-model="requestForm.purchaseContractCode"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="合同名称：" prop="purchaseContractName">
                    <el-input
                      v-model="requestForm.purchaseContractName"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      :maxlength="20"
                    />
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                
                >
                  <el-form-item label="合同内容：" prop="conContent">
                    <el-input
                      :maxlength="20"
                      v-model="requestForm.conContent"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="申请日期：" prop="applicantDate">
                    <el-date-picker
                      v-model="requestForm.applicantDate"
                      format="YYYY/MM/DD"
                      class="search-input"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="请选择"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办人：" prop="applicantId">
                    <el-select
                      filterable
                      v-model="requestForm.applicantId"
                      placeholder="请选择"
                      clearable
                      class="search-input"
                      @change="handleUserChange"
                      value-key="userId"
                      placement="bottom-end"
                    >
                      <!-- <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :label="dict.nickName"
                        :value="dict.userId"
                      /> -->
                      <el-option disabled :value="null">
                        <div class="auto-top">
                          <span class="auto-item">人员姓名</span>
                          <span class="auto-item">联系方式</span>
                          <span class="auto-item">职位</span>
                          <span class="auto-item">部门</span>
                        </div>
                      </el-option>
                      <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :value="dict.userId"
                        :label="dict.nickName"
                      >
                        <div style="display: flex">
                          <div class="auto-item" :title="dict.nickName">
                            {{ dict.nickName }}
                          </div>
                          <div class="auto-item" :title="dict.phonenumber">
                            {{ dict.phonenumber ? dict.phonenumber : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.postName">
                            {{ dict.postName ? dict.postName : "--" }}
                          </div>
                          <div class="auto-item" :title="dict.fullDeptName">
                            {{ dict.fullDeptName ? dict.fullDeptName : "--" }}
                          </div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="经办部门：">
                    <el-input
                      disabled
                      v-model="requestForm.deptName"
                      placeholder="自动获取"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>

          
              
                <el-col
                  :span="6"
              
                >
                  <el-form-item label="甲方单位：" prop="partyUnits">
                    <el-select
                      :placeholder="'请选择'"
                      placement="bottom-end"
                      v-model="requestForm.customerId"
                      clearable
                      class="search-input"
                    >
                    <el-option
                      v-for="dict in customerList"
                      :key="dict.customerId"
                      :label="dict.name"
                      :value="dict.customerId"
                    />
                    </el-select>
                  </el-form-item>
                </el-col>
            

                <el-col
                  :span="6"
                >
                  <el-form-item label="印章归属：" prop="ownershipSeal">
                    <el-select
                      :placeholder="'请选择'"
                      placement="bottom-end"
                      v-model="requestForm.ownershipSeal"
                      clearable
                      class="search-input"
                    >
                      <el-option
                        v-for="dict in partyUnitsList"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

               

                
                
                <el-col :span="6">
                  <el-form-item label="合同金额：" prop="contractAmount">
                    <el-input
                      type="Number"
                      v-model="requestForm.contractAmount"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    >
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
             
                <el-col
                  :span="6"
                >
                  <el-form-item label="用印文件：" prop="printedDocuments">
                    <el-input
                      type="Number"
                      v-model="requestForm.printedDocuments"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      :max="99"
                    >
                      <template #append>份</template>
                    </el-input>
                  </el-form-item>
                </el-col>
             
               
                <el-col :span="6">
                  <el-form-item label="应归档份数：" prop="pigeonholeNumber">
                    <el-input
                      v-model="requestForm.pigeonholeNumber"
                      type="Number"
                      placeholder="请输入"
                      clearable
                      :max="99"
                      class="search-input"
                    >
                      <template #append>份</template></el-input
                    >
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6"
                
                >
                  <el-form-item label="合同备注：" prop="remarks">
                    <el-input
                      :maxlength="20"
                      v-model="requestForm.remarks"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                    <el-col
                      :span="6"
                    >
                      <el-form-item label="合同附件：" prop="suppFileInfoVos">
                        <Upload
                          :fileList="requestForm.suppFileInfoVos"
                          :isFull="true"
                          :limit="10"
                          :showButton="true"
                          @success="(result) => uploadSuccess(result)"
                          @deleteFile="(result) => uploadRemove(result)"
                          :isCanDelete="pageType == 'detail' ? false : true"
                          :disabled="pageType == 'detail'"
                        />
                        <!-- accept=".jpg,.png" -->
                      </el-form-item>
                    </el-col>
                  </el-row>
             
            </el-form>
              </div>
            </el-collapse-item>
            <!-- 添加物料 -->
            <el-collapse-item
              name="2"
              style="position: relative"
              v-if="contactAddShow"
              class="transform-up"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">添加物料</span>
                <div class="search-button button-position" v-if="false">
                  <el-button class="btn save" @click.stop="handleHand"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >手动添加</el-button
                  >
                  <el-button class="btn submit" @click.stop="handleMaterial"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >选择物料</el-button
                  >
                </div>
              </template>
              <div class="request-info">
                <el-form
                  :model="contactForm"
                  ref="contactFormRef"
                  :rules="queryContactRules"
                  label-width="100px"
                  v-enterToNext
                >
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="物料编号：">
                        <el-input
                          v-model="contactForm.materialCode"
                          placeholder="自动生成"
                          clearable
                          class="search-input"
                          disabled=""
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="物料名称：" prop="materialName">
                        <el-input
                          :disabled="contactForm.materialCode !== ''"
                          ref="refInput"
                          v-model="contactForm.materialName"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="出厂型号：" prop="factoryCode">
                        <el-input
                          :disabled="contactForm.materialCode !== ''"
                          v-model="contactForm.factoryCode"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="技术参数："
                        prop="technologyParameter"
                      >
                        <el-input
                          :disabled="contactForm.materialCode !== ''"
                          v-model="contactForm.technologyParameter"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="0">
                    <el-col :span="6">
                      <el-form-item label="单位：" prop="materialUnit">
                        <el-select
                          :disabled="contactForm.materialCode !== ''"
                          v-model="contactForm.materialUnit"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleUnitChange"
                        >
                          <el-option
                            v-for="dict in unitList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="采购数量：" prop="purchaseNumber">
                        <!-- disabled -->
                        <el-input
                          type="Number"
                          v-model="contactForm.purchaseNumber"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        />
                      </el-form-item>
                    </el-col>

                    <!-- </el-row>
              <el-row> -->
                    <el-col :span="6">
                      <el-form-item label="采购单价：" prop="purchasePrice">
                        <el-input
                          type="Number"
                          v-model="contactForm.purchasePrice"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="税率：" prop="taxRate">
                        <!-- <el-input
                      type="Number"
                      v-model="contactForm.taxRate"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>%</template>
                    </el-input> -->
                        <el-select
                          v-model="contactForm.taxRate"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handlePrice"
                        >
                          <el-option
                            v-for="dict in taxRateList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="税额：">
                        <el-input
                          pattern="/^\d+(\.\d{1,2})?$/"
                          disabled
                          type="Number"
                          v-model="contactForm.taxAmount"
                          placeholder="单价、自动计算"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="不含税金额：">
                        <el-input
                          disabled
                          type="Number"
                          v-model="contactForm.noTaxAmount"
                          placeholder="单价、自动计算"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="总金额：">
                        <el-input
                          disabled
                          v-model="contactForm.allPrice"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="运费：" prop="freight">
                        <el-input
                          type="Number"
                          v-model="contactForm.freight"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="发票类型：" prop="invoiceType">
                        <el-select
                          v-model="contactForm.invoiceType"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                        >
                          <el-option
                            v-for="dict in invoiceTypeList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="到货周期：" prop="deliveryCycle">
                        <el-input
                          v-model="contactForm.deliveryCycle"
                          placeholder="如：一周内。方便采购了解优先级，以保障供应时效"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="requestForm.contractType == 4">
                      <el-form-item label="渠道：">
                        <el-select
                          v-model="contactForm.channel"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          :disabled="requestForm.purchaseOrderId ? true : false"
                          @change="changeChannel"
                        >
                          <el-option
                            v-for="dict in channelList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6" v-if="requestForm.contractType == 4">
                      <el-form-item label="供应商：">
                        <el-autocomplete
                          popper-class="autoclass"
                          v-model="contactForm.supplierName"
                          :fetch-suggestions="querySearch"
                          placeholder="请输入"
                          @select="handleSuppliereSelect($event, 1)"
                          style="width: 268px"
                          clearable
                          placement="bottom-end"
                          :disabled="requestForm.purchaseOrderId ? true : false"
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div class="auto-item">供应商编号</div>
                              <div class="auto-item">供应商简称</div>
                              <div class="auto-item">供应商全称</div>
                              <div class="auto-item">供应商地址</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div class="auto-item" :title="item.supplierCode">
                                {{ item.supplierCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.supplierAbbreviation"
                              >
                                {{ item.supplierAbbreviation }}
                              </div>
                              <div class="auto-item" :title="item.supplierName">
                                {{ item.supplierName }}
                              </div>
                              <div
                                class="auto-item"
                                :title="`${item.provinceName}${item.cityName}${item.areaName}`"
                              >
                                {{ item.provinceName }}{{ item.cityName
                                }}{{ item.areaName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                      <!-- <el-form-item label="供应商：" prop="distributorName">
                    <el-input
                      v-model="contactForm.distributorName"
                      placeholder=""
                      clearable
                      class="search-input"
                      :disabled="requestForm.purchaseOrderId?true:false"
                    />
                  </el-form-item> -->
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-item>
            <!-- 框架协议列表 -->
            <el-collapse-item
              name="5"
              style="position: relative; margin: 20px 0"
              :class="!contactAddShow ? 'transform-down' : ''"
              v-if="requestForm.contractType === 3"
            >
              <!--  && requestForm.frameworkId -->
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">框架协议列表</span>
              </template>
              <div class="contact-info">
                <!-- 表格数据 -->
                <el-table
                  :data="requestForm.purchaseConMaterialByIdRespVos"
                  border
                  :height="'100%'"
                  :header-cell-style="{ 'text-align': 'center' }"
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    width="70"
                    align="center"
                  />
                  <el-table-column
                    label="物料编号"
                    prop="materialCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #default="{ row }">
                      <span>{{
                        row.materialCode ? row.materialCode : "--"
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />

                  <el-table-column
                    label="出厂型号"
                    prop="factoryCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="技术参数"
                    prop="technologyParameter"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="单位"
                    prop="materialUnitName"
                    :show-overflow-tooltip="true"
                    min-width="100"
                  />
                  <el-table-column
                    label="采购数量"
                    prop="purchaseNumber"
                    :show-overflow-tooltip="true"
                    min-width="100"
                  />

                  <el-table-column
                    label="已用数量"
                    prop="usedQuantity"
                    :show-overflow-tooltip="true"
                    min-width="100"
                  />

                  <el-table-column
                    label="剩余数量"
                    prop="remainingQuantity"
                    :show-overflow-tooltip="true"
                    min-width="100"
                  />

                  <el-table-column
                    label="本次使用数量"
                    prop="quantity"
                    :show-overflow-tooltip="true"
                    width="300"
                  >
                    <template #default="{ row, $index }">
                      <el-input
                        v-if="pageType === 'add' || pageType === 'edit'"
                        type="Number"
                        v-model="row.quantity"
                        placeholder="请输入"
                        clearable
                      />
                      <!-- class="search-input" -->
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
           
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="审批进度" name="approval">
          <div id="print-iframe" v-if="flowInfoList.length">
            <!-- 步骤栏 -->
            <div :class="printFlag ? 'steps-print-box' : 'steps-box'" style="height:100%;">
              <el-steps
                direction="vertical"
                :class="flowInfoList.length > 7 ? 'BigSteps' : 'SmallSteps'"
                :active="flowingStep"
                finish-status="success"
              >
                <el-step v-for="(item, index) in flowInfoList" :key="index">
                  <template #title>
                    <div class="steps-top">
                      <div :title="item.name" style="width: 200px">
                        {{ item.name }}
                      </div>
                      <span class="steps-time">{{ item.createTime }}</span>
                    </div>
                  </template>
                  <template #description>
                    <div
                      class="steps-box-info"
                      v-if="item.auditEmpList && item.auditEmpList.length"
                    >
                      <div
                        v-for="(child, index) in item.auditEmpList"
                        :key="index"
                      >
                        <div class="ription">
                          {{ child.createUserName }} {{ child.resultName }}
                        </div>
                        <div class="ription" v-if="child.remark">
                          处理意见： {{ child.remark }}
                        </div>
                        <div
                          class="line"
                          v-if="index + 1 != item.auditEmpList.length"
                        ></div>
                      </div>
                    </div>
                  </template>
                </el-step>
              </el-steps>
            </div>
            <!-- 表格数据 -->
            <el-table
              v-if="false"
              :data="auditList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              sum-text=""
            >
              <!-- 操作模式 -->
              <el-table-column label="流程节点" prop="name" min-width="120">
              </el-table-column>
              <el-table-column
                label="审核人"
                prop="createUserName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核时间"
                prop="createTime"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核意见"
                prop="resultName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column label="审核备注" prop="remark" min-width="120">
              </el-table-column>
            </el-table>
          </div>
          <div v-else>暂无审核</div>
        </el-tab-pane>
        <el-tab-pane label="归档文档" name="nodswe">
          <Contractcustodian
            v-if="
              activeName == 'nodswe' && requestForm.archiveVo.flowIntype == 2
            "
            ref="ContractcustodianRef"
            @handleBack="handleBack"
            :requestForm="requestForm"
            :pagestatus="pagestatus"
            :modeltype="'sealcontract'"
          ></Contractcustodian>
          <Subapplicant
            v-if="
              activeName == 'nodswe' && requestForm.archiveVo.flowIntype == 1
            "
            @handleBack="handleBack"
            :requestForm="requestForm"
            :pagestatus="pagestatus"
            :modeltype="'sealcontract'"
          ></Subapplicant>
          <div
            v-if="
              activeName == 'nodswe' && requestForm.archiveVo.flowIntype == 0
            "
          >
            暂无归档
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 选择物料 -->
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      :RequestChooseList="requestForm.purchaseContractMaterialRespVos"
      :materialAllList="materialAllList"
      :purchaseOrderId="requestForm.purchaseOrderId"
      @submitChoose="handleSelectMaterial"
    />
    <!-- 到票 -->
    <RequestAdd
      ref="requestAddRef"
      v-if="requestAddShow"
      v-model:requestAddShow="requestAddShow"
      @refreshList="getTicketList"
      :contractId="requestForm.purchaseContractId"
      :contractCode="requestForm.purchaseContractCode"
      :pageType="ticketPageType"
    />
    <!-- 付款申请 -->
    <PaymentAdd
      ref="paymentAddRef"
      v-if="paymentAddShow"
      v-model:requestAddShow="paymentAddShow"
      @refreshList="getPaymentList"
      :contractId="requestForm.purchaseContractId"
      :contractCode="requestForm.purchaseContractCode"
      :pageType="paymentPageType"
    />
    <!-- 入库记录 -->
    <InorderAdd
      v-if="inorderAddShow"
      v-model:addShow="inorderAddShow"
      @refreshList="getInorderList"
      :contractId="requestForm.purchaseContractId"
      :contractCode="requestForm.purchaseContractCode"
      :supplierName="requestForm.distributorName"
      :pageType="inorderPageType"
    />

    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="''"
      v-model="evaluateDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="评论内容：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="evaluateInfo"
          placeholder=""
          type="textarea"
          rows="5"
          maxlength="500"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="saveEvaluate()"
            >保存</el-button
          >

          <el-button style="background-color: #fff" @click="closeEvaluate()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { addEvaluateApi, getEvaluateListApi } from "@/api/pub.js";
import RequestAdd from "./requestAdd.vue";
import InorderAdd from "../../stock/inorder/add.vue";
import Subapplicant from "../../seal/circulation/subapplicant";
import Contractcustodian from "../../seal/circulation/contractcustodian";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import { getUserListApi } from "@/api/information/customer";
import {
  getOrderMaterialApi,
  getRequestListApi,
  getRequestAllListApi,
  getRequestFilterListApi,
  getTicketListApi,
  getInorderListApi,
  deleteTicketApi,
  checkSealApi,
  getFrameDetailListApi,
  selectAuditList,
} from "@/api/purchase/contractSeal";
import {
  getCustomerAllListApi,
} from "@/api/information/customer";
import {

  getSealDetailApi,

} from "@/api/serve/contractSeal";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
import { deletePaymentId } from "@/api/purchase/payment";

const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "contractSealDtlShow",
  // 更新客户新增组件显隐
  "update:contractSealDtlShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
const activeName = ref("info");
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5", "6", "7"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);

// 选择审核
const auditDialogShow = ref(false);
const loadingCheck = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 合同类型列表
const typeList = ref([]);
// 发票类型
const invoiceTypeList = ref([]);

let auditList = ref([]);

// 采购类型列表
const purchaseDefaultList = ref([]);
const purchaseTypeList = ref([]);
// 单位列表
const unitList = ref([]);
// 采购订单列表
const orderList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 解除列表
const relieveList = ref([]);
// 项目列表
const projectList = ref([]);
// 请购列表
const requestList = ref([]);
const requestAllList = ref([]);
const requestFilterList = ref([]);
// 采购物料列表
const materialAllList = ref([]);
// 原合同列表
const sourceContractList = ref([]);
const sourceContractList2 = ref([]);
// 合同用印到票列表
const ticketList = ref([]);
// 付款列表
const paymentList = ref([]);
// 入库列表
const inorderList = ref([]);
// 框架协议列表
const frameList = ref([]);
// 到票操作类型
const ticketPageType = ref("");
// 付款操作类型
const paymentPageType = ref("");
// 入库操作类型
const inorderPageType = ref("");
// 客户新增组件显隐
const requestAddShow = ref(false);
// 付款新增组件显隐藏
const paymentAddShow = ref(false);
// 入库新增组件显隐藏
const inorderAddShow = ref(false);
// 到票新增组件引用
const requestAddRef = ref(null);
// 合同用印id
const sealId = ref(null);
//渠道列表
const channelList = ref([]);
// 默认税率列表
const taxRateList = ref([]);
// 甲方单位
const customerList = ref([]);
const partyUnitsList = ref([]);

const paymentAddRef = ref(null);

//审核进度数据
const flowInfoList = ref([]);
//当前进度
const flowingStep = ref(0);

// 评论
const evaluateDialogShow = ref(false);
// 评论内容
const evaluateInfo = ref("");
// 评论列表
const evaluateList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  remarks: "", // 备注
  type: 0, // 	按钮类型0：存为草稿；1；提交
  deptName: "", // 申请部门
  purchaseProjectListRespVos: [], // 关联项目id
  contractAmount: null,
  contractCheckStatus: null, // 审核状态
  contractType: null, // 合同类型
  frameworkId: null, // 关联框架协议i
  printedDocuments: null, // 	用印文件
  purchaseContractCode: "", // 采购合同编号
  purchaseContractMaterialRespVos: [], // 合同用印物料信息对象
  purchaseContractName: "", // 	采购合同名称
  purchaseInqMaterialDetailLitsRespVos: [], // 	请购单物料信息
  purchaseConMaterialByIdRespVos: [], // 	框架协议明细
  purchaseOrderId: null, // 	采购单id
  purchaseType: null, // 	采购类型
  secureReason: "", // 	解除的原因
  sourceContract: "", // 	原合同ID
  sourceContractName: "", //原合同名称
  suppFileInfoVos: [], // 	合同附件
  supplierId: null, // 供应商id
  supplierName: "", // 供应商名称
};
// 联系人表单数据模板
const contactFormTemplate = {
  deliveryCycle: "", // 到货周期
  factoryCode: "", // 出厂编号
  manufactureName: "", // 生产厂商名称
  manufacturerId: null, // 生产厂商(也是供应商id)
  manufacturerIdName: "", // 生产厂商全称（详情专用）
  materialCode: "", // 	物料编号
  materialName: "", // 	物料名称
  materialUnit: null, // 	物料单位
  materialUnitName: "", // 物料单位中文
  purchaseApplyId: null, // 关联请购申请表主键id
  purchaseMaterialId: null,
  purchaseNumber: null, // 请购数量
  purchasePrice: null, // 	请购单价
  allPrice: null, // 总价
  purchaseTrackingStatus: null, // 请购跟踪状态
  purchaseTrackingStatusName: "", // 	请购跟踪状态中文
  referenceLink: "", // 参考链接
  remarks: "", // 备注
  suppFileInfoVos: [], // 采购申请物料图片
  supplierId: null, // 供应商id
  supplierIdName: "", // 供应商全称（详情专用）
  supplierName: "", // 供应商名称
  technologyParameter: "", // 技术参数
  channel: null, //渠道
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择经办人", trigger: "change" },
    ],
    contractType: [
      { required: true, message: "请选择合同类型", trigger: "change" },
    ],
    purchaseType: [
      { required: true, message: "请选择采购类型", trigger: "change" },
    ],
    purchaseInqMaterialDetailLitsRespVos: [
      { required: true, message: "请选择关联请购单", trigger: "change" },
    ],
    purchaseContractName: [
      { required: true, message: "请输入合同名称", trigger: "blur" },
    ],
    supplierName: [
      { required: true, message: "请输入供应商", trigger: "blur" },
    ],
    supplierId: [
      { required: true, message: "请选择供应商", trigger: "change" },
    ],
    contractAmount: [
      { required: true, message: "请输入合同金额", trigger: "blur" },
      // { min: 1, max: 20, message: "金额数不能超过20个字符", trigger: "blur" },
    ],
    sourceContractName: [
      { required: true, message: "请选择原合同", trigger: "change" },
    ],
    secureReason: [
      { required: true, message: "请选择解除原因", trigger: "change" },
    ],
    printedDocuments: [
      { required: true, message: "请选择用印文件", trigger: "change" },
      { min: 0, max: 2, message: "用印文件为0到99之间的整数", trigger: "blur" },
    ],
    pigeonholeNumber: [
      { required: true, message: "请输入应归档份数", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 1 || value > 99) {
            callback(new Error("应归档份数为0到99之间的整数"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    frameworkId: [
      { required: true, message: "请选择关联框架协议", trigger: "change" },
    ],
    // purchaseOrderId: [
    //   { required: true, message: "请选择关联采购单", trigger: "change" },
    // ],
    suppFileInfoVos: [
      { required: true, message: "请上传合同附件", trigger: "change" },
    ],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      { required: true, message: "请输入物料名称", trigger: "blur" },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入采购数量", trigger: "blur" },
    ],
    budgetedPrice: [
      { required: true, message: "请输入预算单价", trigger: "blur" },
    ],
    purchasePrice: [
      { required: true, message: "请输入询价单价", trigger: "blur" },
    ],
    taxRate: [{ required: true, message: "请输入税率", trigger: "blur" }],
    freight: [{ required: true, message: "请输入运费", trigger: "blur" }],
    invoiceType: [
      { required: true, message: "请选择发票类型", trigger: "change" },
    ],
    deliveryCycle: [
      { required: true, message: "请输入到货周期", trigger: "blur" },
    ],
    channel: [{ required: true, message: "请选择渠道", trigger: "change" }],
  },
  // 角色列表
  contactTypeList: [],
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
  auditRemark,
  auditResult,
  applyId,
} = toRefs(data);

import print from "vue3-print-nb";

// 使用自定义指令
const vPrint = print;
const printFlag = ref(false);

let prints = {
  id: "print-iframe",
  popTitle: "配置页眉标题", // 打印配置页上方的标题
  extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  // 开始打印之前的callback
  beforeOpenCallback() {
    console.log("开始打印之前！");
  },
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
    printFlag.value = false;
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
  },
  standard: "",
  extarCss: "",
};

let pagestatus = ref("detail");

const handlePrint = () => {
  printFlag.value = true;
};

// 处理评论按钮点击
const handleEvaluate = () => {
  evaluateDialogShow.value = true;
};

// 保存评论
const saveEvaluate = async () => {
  if (!evaluateInfo.value) return ElMessage.info("请输入评论内容！");
  const data = {
    businessId: requestForm.value.purchaseContractId,
    content: evaluateInfo.value,
    modelType: 5,
  };
  const result = await addEvaluateApi(data);
  if (result.code === 200) {
    ElMessage.success(result.msg);
    evaluateDialogShow.value = false;
    evaluateInfo.value = "";
    getEvaluateList();
  }
};

// 关闭评论弹窗
const closeEvaluate = () => {
  evaluateDialogShow.value = false;
  evaluateInfo.value = "";
};

// 获取评价列表
const getEvaluateList = async () => {
  const data = {
    businessId: requestForm.value.purchaseContractId,
    modelType: 5,
  };
  const result = await getEvaluateListApi(data);
  evaluateList.value = result.data || [];
};

const handleCheckBtn2 = (requestFormRef, type, title) => {
  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  (applyId.value = requestForm.value.purchaseContractId),
    (auditDialogShow.value = true);
  loadingCheck.value = false;
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  const obj = {
    approvalStatus: auditResult.value,
    purchaseContractId: applyId.value,
    auditRemark: auditRemark.value,
  };
  try {
    loadingCheck.value = true;
    const res = await checkSealApi(obj);
    auditDialogShow.value = false;

    //loadingCheck.value =false;

    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
  } catch (error) {
    loadingCheck.value = false;

    // ElMessage.error(error);
  }
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

// tab改变
let ContractcustodianRef = ref(null);
const activeNamechange = (value) => {
  if (value == "nodswe") {
    if (requestForm.value.archiveVo.flowIntype == 2) {
      nextTick(() => {
        ContractcustodianRef.value.handlerdetail();
      });
    }
  }
};

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  if (!requestFormRef) return;
  await requestFormRef.validate(async (valid, fields) => {
    if (valid) {
      let materialRespVos = requestForm.value.purchaseContractMaterialRespVos;
      if (materialRespVos && materialRespVos.length > 0) {
        let visible = materialRespVos.find(
          (element) => element.purchaseNumber == undefined
        );
        if (visible == undefined) {
          ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "confirmBtnClass",
            cancelButtonClass: "cancelBtnClass",
          })
            .then(async () => {
              requestForm.value.type = type;
              let res;
              if (!requestForm.value.purchaseContractId) {
                // 新增客户
                res = await addSealApi(requestForm.value);
              } else {
                // 编辑客户
                res = await editSealApi(requestForm.value);
              }
              if (res.code === 200) {
                emit("update:contractSealDtlShow", false);
                emit("refreshList", false);
                ElMessage.success(res.msg);
                requestForm.value = JSON.parse(
                  JSON.stringify(requestFormTemplate)
                );
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch(() => {});
        } else {
          ElMessage({
            message: "请完善物料信息",
            type: "warning",
          });
        }
      } else {
        ElMessage({
          message: "请选择物料信息",
          type: "warning",
        });
      }
    }
  });
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:contractSealDtlShow", false);
    emit("refreshList", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:contractSealDtlShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  requestForm.contractType;
  if (requestForm.value.contractType !== null) {
    selectionMaterialShow.value = true;
  } else {
    ElMessage.warning("请先选择合同类型");
  }
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value.length) {
    requestForm.value.purchaseContractMaterialRespVos.push(...value);
    selectionMaterialShow.value = false;
    if (requestForm.value.purchaseOrderId) {
      handleRequest();
    }
  } else {
    ElMessage.info("请选择物料");
  }
};
/* 选择渠道 */
const changeChannel = (row) => {
  var obj = {};
  obj = channelList.value.find(function (i) {
    return i.value === row;
  });
  contactForm.value.channelName = obj.label;
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value, index) => {
  if (index == 1) {
    contactForm.value.supplierId = value.supplierId;
  } else {
    requestForm.value.supplierId = value.supplierId;
  }
};

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
/* 原合同input框搜索 */
const contractSearch = (queryString, cb) => {
  const results = queryString
    ? sourceContractList.value.filter(createFilter(queryString))
    : sourceContractList.value;
  cb(results);
};

const handleContractSelect = (value) => {
  requestForm.value.sourceContract = value.purchaseContractId;
  requestForm.value.supplierName = value.distributorName;
  requestForm.value.supplierId = value.supplierId;
};

const handleContractSelect2 = (value) => {
  if (value) {
    sourceContractList2.value.forEach((item) => {
      if (item.purchaseContractId == value) {
        requestForm.value.originType = item.contractType;
      }
    });
  } else {
    requestForm.value.originType = null;
  }
};

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const obj = {
        contractCheckStatus: type,
        purchaseContractId: requestForm.value.purchaseContractId,
        purchaseInqMaterialDetailLitsRespVos:
          requestForm.value.purchaseInqMaterialDetailLitsRespVos,
        purchaseOrderId: requestForm.value.purchaseOrderId,
      };
      const res = await checkSealApi(obj);
      if (res.code === 200) {
        emit("update:contractSealDtlShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 处理类型选择
 * @param {Number} value 选择值
 */
const handleType = (value) => {
  let name = "";
  if (value == 3) {
    name = "协议采购";
  } else if (value == 4) {
    name = "小额垫付";
  } else {
    name = requestForm.value.purchaseContractName;
    // name = "";
  }
  requestForm.value = {
    ...requestFormTemplate,
    purchaseContractCode: requestForm.value.purchaseContractCode,
    purchaseContractName: name,
    applicantDate: requestForm.value.applicantDate,
    applicantId: requestForm.value.applicantId,
    deptName: requestForm.value.deptName,
    contractType: requestForm.value.contractType,
  };
  /* 根据合同类型修改采购类型 */
  let targetArr = [];
  if (value == 0 || value == 3) {
    targetArr = ["低空防御", "周界防护"];
  } else if (value == 1) {
    targetArr = [
      "固定资产",
      "员福礼品",
      "项目申报",
      "租赁装修",
      "行政月结",
      "人资服务",
      "企划制作",
      "法务财务",
      "其他服务",
    ];
  }
  if (targetArr.length == 0) {
    purchaseTypeList.value = [...purchaseDefaultList.value];
  } else {
    purchaseTypeList.value = purchaseDefaultList.value.filter(
      (obj) => targetArr.indexOf(obj.label) !== -1
    );
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理请购单选择
 * @param {Number} value 选择值
 */
const handleRequestChange = () => {
  requestForm.value.purchaseProjectListRespVos = [];
  requestForm.value.purchaseInqMaterialDetailLitsRespVos.forEach((item) => {
    // 判断当前请购单有项目且项目只有一个
    if (
      item.projectId &&
      !requestForm.value.purchaseProjectListRespVos.some(
        (itemArr) => itemArr.projectId === item.projectId
      )
    ) {
      requestForm.value.purchaseProjectListRespVos.push({
        projectCode: item.projectCode,
        projectId: item.projectId,
        projectName: item.projectName,
      });
    }
  });
};

/**
 * @description: 处理采购单选择
 * @param {Number} value 选择值
 */
const handleSupplierChange = async (value) => {
  requestForm.value.frameworkId = null;
  requestForm.value.purchaseConMaterialByIdRespVos = [];
  // if (value) {
    // 框架协议
    // await getFrameSelectListApi(value).then((res) => {
    //   if (res) {
    //     frameList.value = res;
    //   }
    // });
  // } else {
  //   frameList.value = [];
  // }
};



/**
 * @description: 处理采购单选择
 * @param {Number} value 选择值
 */
const handleOrderChange = async (value) => {
  // 回显物料信息
  const res = await getOrderMaterialApi({
    contractType: requestForm.value.contractType,
    purchaseOrderId: requestForm.value.purchaseOrderId,
  });
  if (res) {
    // requestForm.value.purchaseInqMaterialDetailLitsRespVos = [];
    // requestForm.value.purchaseProjectListRespVos = [];
    materialAllList.value = [];
    materialAllList.value = JSON.parse(JSON.stringify(res));
    requestForm.value.purchaseContractMaterialRespVos = res;
    // 回显请购单列表
    handleRequest();
  }
  // requestList.value = requestForm.value.purchaseInqMaterialDetailLitsRespVos;
  // 请购单列表
  //
};

/**
 * @description: 处理物料回显请购单
 */
const handleRequest = () => {
  requestForm.value.purchaseInqMaterialDetailLitsRespVos = [];
  requestForm.value.purchaseProjectListRespVos = [];
  requestForm.value.purchaseContractMaterialRespVos.forEach((item) => {
    item.allPrice =
      item.purchasePrice * item.purchaseNumber +
      (item.freight ? item.freight : 0);
    item.purchaseInqMaterialDetailLitsRespVos.forEach((reqItem) => {
      // if(reqItem.purchaseTrackingStatus === 1) {
      requestForm.value.purchaseInqMaterialDetailLitsRespVos.push(reqItem);
      // 判断当前请购单有项目且项目只有一个
      if (
        reqItem.projectId &&
        !requestForm.value.purchaseProjectListRespVos.some(
          (itemArr) => itemArr.projectId === reqItem.projectId
        )
      ) {
        requestForm.value.purchaseProjectListRespVos.push({
          projectCode: reqItem.projectCode,
          projectId: reqItem.projectId,
          projectName: reqItem.projectName,
        });
      }
      // }
    });
  });
};

/**
 * @description: 获取关联请购单列表
 */
const getRequestList = async () => {
  const res = await getRequestListApi({
    purchaseContractId: requestForm.value.purchaseContractId,
  });
  if (res) {
    requestList.value = res;
  }
  const res2 = await getRequestAllListApi({
    checkStatus: 3,
    purchaseContractId: requestForm.value.purchaseContractId,
  });
  requestAllList.value = [];
  if (res2) {
    requestAllList.value = res2;
  }

  const res3 = await getRequestFilterListApi();
  requestFilterList.value = [];
  if (res3) {
    requestFilterList.value = res3;
  }
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = () => {
  // 预算： 单价*数量
  if (contactForm.value.budgetedPrice && contactForm.value.purchaseNumber) {
    contactForm.value.budgeteAllPrice = (
      contactForm.value.budgetedPrice * contactForm.value.purchaseNumber
    ).toFixed(2);
  }
  // 总金额： 单价*数量+运费
  if (contactForm.value.purchasePrice && contactForm.value.purchaseNumber) {
    let freight = contactForm.value.freight
      ? Number(contactForm.value.freight)
      : 0;
    contactForm.value.allPrice = (
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber +
      freight
    ).toFixed(2);
  }
  // 税额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxRate) {
    contactForm.value.taxAmount = (
      (contactForm.value.purchasePrice /
        (1 + contactForm.value.taxRate * 0.01)) *
      contactForm.value.taxRate *
      0.01
    ).toFixed(2);
  }

  // 不含税金额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxAmount) {
    contactForm.value.noTaxAmount = (
      contactForm.value.purchasePrice - contactForm.value.taxAmount
    ).toFixed(2);
  }
};

/**
 * @description: 新增到票
 */
const handleAddTicket = () => {
  ticketPageType.value = "add";
  requestAddShow.value = true;
};

/**
 * @description: 新增付款申请
 */
const handleAddPayment = () => {
  paymentPageType.value = "add";
  paymentAddShow.value = true;
};

/**
 * @description: 新增入库
 */
const handleAddInorder = () => {
  inorderPageType.value = "add";
  inorderAddShow.value = true;
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef) => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        requestForm.value.purchaseContractMaterialRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
      } else {
        requestForm.value.purchaseContractMaterialRespVos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      nextTick(() => {
        refInput.value.focus();
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.suppFileInfoVos.push({ ...response, businessType: 7 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  contactAddShow.value = true;
  operateType.value = "add";
  nextTick(() => {
    refInput.value.focus();
  });
};

/**
 * @description: 联系人返回
 */
const handleRequestBack = () => {
  contactAddShow.value = false;
  nextTick(() => {
    refSelect.value.focus();
  });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  if (data) {
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = "合计";
        return;
      }
      const values = data.map((item) => Number(item[column.property]));
      // 只对amount这一列进行总计核算。
      if (
        column.property === "purchaseNumber" ||
        column.property === "budgetedPrice" ||
        column.property === "purchasePrice" ||
        // column.property === "taxRate" ||
        column.property === "taxAmount" ||
        column.property === "freight" ||
        column.property === "noTaxAmount" ||
        column.property === "allPrice" ||
        column.property === "budgeteAllPrice"
      ) {
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.property !== "purchaseNumber") {
            sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
          }
          // sums[index] += "元";
        } else {
          sums[index] = "";
        }
      }
    });
    if (props.pageType === "add" || props.pageType === "edit") {
      // sums[16] = sums[11] * sums[8] + sums[15];
      // sums[10] = sums[9] * sums[8];
      // sums[15] = null;
      // 14总价 9单价 6数量
      // sums[15] = sums[10] * sums[7] + sums[14];
      // sums[9] = sums[8] * sums[7];
      // sums[14] = null;
    } else {
      // sums[16] = sums[11] * sums[8] + sums[15];
      // sums[10] = sums[9] * sums[8];
      // sums[15] = null;
      // 14总价 9单价 6数量
      // sums[15] = sums[10] * sums[7] + sums[14];
      // sums[9] = sums[8] * sums[7];
      // sums[14] = null;
    }
    return sums;
  }
};

/**
 * @description: 处理合计
 */
const getSummariesTicket = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (column.property === "invoiceAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

/**
 * @description: 处理合计
 */
const getSummariesPaymentList = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (data && data.length) {
      const values = data.map((item) => Number(item[column.property]));
    }
    // 只对amount这一列进行总计核算。
    if (column.property === "invoiceAmount") {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = {
      ...JSON.parse(JSON.stringify(row)),
      suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
        ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
        : [],
    };
    contactForm.value.allPrice =
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber
        ? (
            contactForm.value.purchasePrice * contactForm.value.purchaseNumber
          ).toFixed(2)
        : null;
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    requestForm.value.purchaseContractMaterialRespVos.splice(tabIndex, 1);
    handleRequest();
  }
};

/**
 * @description: 付款记录表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handlePayOperate = async (type, row) => {
  switch (type) {
    case "edit":
      paymentPageType.value = type;
      paymentAddShow.value = true;
      nextTick(() => {
        paymentAddRef.value.handleDetailInfo(row.paymentApplyId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该付款申请信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deletePaymentId(row.paymentApplyId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            handleDetailInfo(sealId.value);
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleTicketOperate = async (type, row) => {
  switch (type) {
    case "edit":
      ticketPageType.value = type;
      requestAddShow.value = true;
      nextTick(() => {
        requestAddRef.value.handleDetailInfo(row.contractRelationInvoiceId);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该到票信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteTicketApi(row.contractRelationInvoiceId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getTicketList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id) => {
  getDicts();

  sealId.value = id;
  try {
    detailInfoShow.value = true;
    // 合同用印详情接口
    const res = await getSealDetailApi(id);
    if (res) {
      requestForm.value = {...res,suppFileInfoVos:res.suppFileInfoVos || []}
    }
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }

  const resAudit = await selectAuditList(id);
  auditList.value = resAudit.data;
  if (resAudit.data.length) {
      flowInfoList.value = resAudit.data;
      flowingStep.value = resAudit.data[0].flowingStep;
    }
};

/**
 * @description: 处理到票
 * @param {Number} id
 */
const getTicketList = async () => {
  // 合同用印到票列表
  await getTicketListApi(requestForm.value.purchaseContractId).then((res) => {
    if (res) {
      ticketList.value = res;
    }
  });
};

/**
 * @description: 处理付款详情
 * @param {Number} id
 */
const getPaymentList = async () => {
  const res = await getSealDetailApi(sealId.value);
  if (res) {
    paymentList.value = res.payApplyInfoRespVos;
  }
};

/**
 * @description: 处理入库
 * @param {Number} id
 */
const getInorderList = async () => {
  // 合同用印到票列表
  await getInorderListApi(requestForm.value.purchaseContractId).then((res) => {
    if (res) {
      inorderList.value = res;
    }
  });
};

/**
 * @description: 获取字典
 */
 async function getDicts() {
  // 类型
  await getDictsApi("erp_synthesis_contract_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });



  // 甲方单位
  await getDictsApi("erp_ownership_seal").then((res) => {
    if (res.code === 200) {
      partyUnitsList.value = res.data;
    }
  });
  await getCustomerAllListApi().then((res) => {
    customerList.value = res;
  });

 
  



  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });
 

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}

onMounted(() => {
  getDicts();
  getRequestList();
  // if (props.pageType === "add") {
  //   nextTick(() => {
  //     refSelect.value.focus();
  //   });
  // }
});

defineExpose({
  handleDetailInfo,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
  .ription {
    color: #8f8f8f;
    line-height: 16px;
    font-size: 12px;
  }
  :deep(.el-step__head.is-success) {
    color: #3399ff !important;
    border-color: #3399ff;
    position: relative;
  }
  :deep(.el-step__title.is-success) {
    color: #3399ff !important;
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
.el-table {
  border: var(--el-table-border);
}
.steps-time {
  font-size: 14px;
  color: #666666;
  margin-left: 300px;
}
.steps-box-info {
  margin: 30px 0;
  padding: 10px;
  width: 630px;
  min-height: 56px;
  border: 1px solid #e6e6e6;
  .ription {
    margin-bottom: 10px;
  }
  .line {
    width: 100%;
    border: 1px solid #e6e6e6;
    margin-bottom: 10px;
  }
}
.steps-top {
  display: flex;
}
</style>
